<!DOCTYPE html>
<html lang=zh>
<head><meta name="generator" content="Hexo 3.9.0">
    <!-- so meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="HandheldFriendly" content="True">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="description" content="前言毕设的小程序要实现分享功能，我将分享功能按照不同的页面分成了三块。分享的内容都是动态定义的，而且因为微信只支持图片分享的模式，所以这里只能使用后端将分享的内容动态写进图片里，最后上传到七牛云，返回一个图片地址 阅读器页面分享就是在阅读章节的时候选择分享，分享出去的图片应当展示的信息包括：书籍封面、书籍名称、章节名称、以及部分章节内容 书籍详情页分享分享出去的图片应当展示的信息包括：书籍封面、书">
<meta name="keywords" content="毕设,nodejs">
<meta property="og:type" content="article">
<meta property="og:title" content="nodejs绘制生成图像">
<meta property="og:url" content="https://andyliwr.github.io/2018/04/23/node_canvas_usage/index.html">
<meta property="og:site_name" content="月光倾城的代码小屋">
<meta property="og:description" content="前言毕设的小程序要实现分享功能，我将分享功能按照不同的页面分成了三块。分享的内容都是动态定义的，而且因为微信只支持图片分享的模式，所以这里只能使用后端将分享的内容动态写进图片里，最后上传到七牛云，返回一个图片地址 阅读器页面分享就是在阅读章节的时候选择分享，分享出去的图片应当展示的信息包括：书籍封面、书籍名称、章节名称、以及部分章节内容 书籍详情页分享分享出去的图片应当展示的信息包括：书籍封面、书">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://file.lantingshucheng.com/1524545631717.png/800x400">
<meta property="og:image" content="https://file.lantingshucheng.com/mbook/share/fa4d3d10-463f-11e8-8a01-25d148dab515.png">
<meta property="og:updated_time" content="2020-01-15T06:30:09.120Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="nodejs绘制生成图像">
<meta name="twitter:description" content="前言毕设的小程序要实现分享功能，我将分享功能按照不同的页面分成了三块。分享的内容都是动态定义的，而且因为微信只支持图片分享的模式，所以这里只能使用后端将分享的内容动态写进图片里，最后上传到七牛云，返回一个图片地址 阅读器页面分享就是在阅读章节的时候选择分享，分享出去的图片应当展示的信息包括：书籍封面、书籍名称、章节名称、以及部分章节内容 书籍详情页分享分享出去的图片应当展示的信息包括：书籍封面、书">
<meta name="twitter:image" content="https://file.lantingshucheng.com/1524545631717.png/800x400">
    
    
        
          
              <link rel="shortcut icon" href="/images/favicon.ico">
          
        
        
          
            <link rel="icon" type="image/png" href="/images/favicon-192x192.png" sizes="192x192">
          
        
        
          
            <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png">
          
        
    
    <!-- title -->
    <title>nodejs绘制生成图像</title>
    <!-- styles -->
    <link rel="stylesheet" href="/css/style.css">
    <!-- persian styles -->
    
      <link rel="stylesheet" href="/css/rtl.css">
    
    <!-- rss -->
    
    
</head>

<body class="max-width mx-auto px3 ltr">
    
      <div id="header-post">
  <a id="menu-icon" href="#"><i class="fas fa-bars fa-lg"></i></a>
  <a id="menu-icon-tablet" href="#"><i class="fas fa-bars fa-lg"></i></a>
  <a id="top-icon-tablet" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');" style="display:none;"><i class="fas fa-chevron-up fa-lg"></i></a>
  <span id="menu">
    <span id="nav">
      <ul>
         
          <li><a href="/">首页</a></li>
         
          <li><a href="/archives/">归档</a></li>
         
          <li><a href="/search/">搜索</a></li>
         
          <li><a href="/tags/">标签</a></li>
         
          <li><a href="/others/">其他文章</a></li>
        
      </ul>
    </span>
    <br/>
    <span id="actions">
      <ul>
        
        <li><a class="icon" href="/2018/04/24/node_gpy_install_fail/"><i class="fas fa-chevron-left" aria-hidden="true" onmouseover="$('#i-prev').toggle();" onmouseout="$('#i-prev').toggle();"></i></a></li>
        
        
        <li><a class="icon" href="/2018/02/12/vue_multiple_pages_develop/"><i class="fas fa-chevron-right" aria-hidden="true" onmouseover="$('#i-next').toggle();" onmouseout="$('#i-next').toggle();"></i></a></li>
        
        <li><a class="icon" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up" aria-hidden="true" onmouseover="$('#i-top').toggle();" onmouseout="$('#i-top').toggle();"></i></a></li>
        <li><a class="icon" href="#"><i class="fas fa-share-alt" aria-hidden="true" onmouseover="$('#i-share').toggle();" onmouseout="$('#i-share').toggle();" onclick="$('#share').toggle();return false;"></i></a></li>
      </ul>
      <span id="i-prev" class="info" style="display:none;">上一篇</span>
      <span id="i-next" class="info" style="display:none;">下一篇</span>
      <span id="i-top" class="info" style="display:none;">返回顶部</span>
      <span id="i-share" class="info" style="display:none;">分享文章</span>
    </span>
    <br/>
    <div id="share" style="display: none">
      <ul>
  <li><a class="icon" href="http://www.facebook.com/sharer.php?u=https://andyliwr.github.io/2018/04/23/node_canvas_usage/"><i class="fab fa-facebook " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://twitter.com/share?url=https://andyliwr.github.io/2018/04/23/node_canvas_usage/&text=nodejs绘制生成图像"><i class="fab fa-twitter " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.linkedin.com/shareArticle?url=https://andyliwr.github.io/2018/04/23/node_canvas_usage/&title=nodejs绘制生成图像"><i class="fab fa-linkedin " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://pinterest.com/pin/create/bookmarklet/?url=https://andyliwr.github.io/2018/04/23/node_canvas_usage/&is_video=false&description=nodejs绘制生成图像"><i class="fab fa-pinterest " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=nodejs绘制生成图像&body=Check out this article: https://andyliwr.github.io/2018/04/23/node_canvas_usage/"><i class="fas fa-envelope " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://getpocket.com/save?url=https://andyliwr.github.io/2018/04/23/node_canvas_usage/&title=nodejs绘制生成图像"><i class="fab fa-get-pocket " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://reddit.com/submit?url=https://andyliwr.github.io/2018/04/23/node_canvas_usage/&title=nodejs绘制生成图像"><i class="fab fa-reddit " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.stumbleupon.com/submit?url=https://andyliwr.github.io/2018/04/23/node_canvas_usage/&title=nodejs绘制生成图像"><i class="fab fa-stumbleupon " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://digg.com/submit?url=https://andyliwr.github.io/2018/04/23/node_canvas_usage/&title=nodejs绘制生成图像"><i class="fab fa-digg " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.tumblr.com/share/link?url=https://andyliwr.github.io/2018/04/23/node_canvas_usage/&name=nodejs绘制生成图像&description="><i class="fab fa-tumblr " aria-hidden="true"></i></a></li>
</ul>

    </div>
    <div id="toc">
      <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#前言"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#阅读器页面分享"><span class="toc-number">1.1.</span> <span class="toc-text">阅读器页面分享</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#书籍详情页分享"><span class="toc-number">1.2.</span> <span class="toc-text">书籍详情页分享</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#小程序首页分享"><span class="toc-number">1.3.</span> <span class="toc-text">小程序首页分享</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#具体实现"><span class="toc-number">2.</span> <span class="toc-text">具体实现</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#安装-node-canvas"><span class="toc-number">2.1.</span> <span class="toc-text">安装 node-canvas</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#基础应用"><span class="toc-number">2.2.</span> <span class="toc-text">基础应用</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#drawImage-的说明"><span class="toc-number">2.3.</span> <span class="toc-text">drawImage 的说明</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#fillText-的说明"><span class="toc-number">2.4.</span> <span class="toc-text">fillText 的说明</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#图片上传七牛云"><span class="toc-number">3.</span> <span class="toc-text">图片上传七牛云</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#效果图"><span class="toc-number">4.</span> <span class="toc-text">效果图</span></a></li></ol>
    </div>
  </span>
</div>

    
    <div class="content index py4">
        
        <article class="post" itemscope itemtype="http://schema.org/BlogPosting">
  <header>
    
    <h1 class="posttitle" itemprop="name headline">
        nodejs绘制生成图像
    </h1>



    <div class="meta">
      <span class="author" itemprop="author" itemscope itemtype="http://schema.org/Person">
        <span itemprop="name">月光倾城的代码小屋</span>
      </span>
      
    <div class="postdate">
        <time datetime="2018-04-23T15:26:51.000Z" itemprop="datePublished">2018-04-23</time>
    </div>


      

      
    <div class="article-tag">
        <i class="fas fa-tag"></i>
        <a class="tag-link" href="/tags/nodejs/">nodejs</a>, <a class="tag-link" href="/tags/毕设/">毕设</a>
    </div>


    </div>
  </header>
  

  <div class="content" itemprop="articleBody">
    <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>毕设的小程序要实现分享功能，我将分享功能按照不同的页面分成了三块。分享的内容都是动态定义的，而且因为微信只支持图片分享的模式，所以这里只能使用后端将分享的内容动态写进图片里，最后上传到七牛云，返回一个图片地址</p>
<h4 id="阅读器页面分享"><a href="#阅读器页面分享" class="headerlink" title="阅读器页面分享"></a>阅读器页面分享</h4><p>就是在阅读章节的时候选择分享，分享出去的图片应当展示的信息包括：书籍封面、书籍名称、章节名称、以及部分章节内容<br><img src="https://file.lantingshucheng.com/1524545631717.png/800x400" alt="章节分享"></p>
<h4 id="书籍详情页分享"><a href="#书籍详情页分享" class="headerlink" title="书籍详情页分享"></a>书籍详情页分享</h4><p>分享出去的图片应当展示的信息包括：书籍封面、书籍名称、作者、书籍类型、以及书籍简介，这块还在开发中，到时候再补进来</p>
<h4 id="小程序首页分享"><a href="#小程序首页分享" class="headerlink" title="小程序首页分享"></a>小程序首页分享</h4><p>这个功能，我想加入到后台管理系统中，让管理员能自定义分享的图片，思路什么的还在考虑中。</p>
<h3 id="具体实现"><a href="#具体实现" class="headerlink" title="具体实现"></a>具体实现</h3><p>说了那么多，直接来看怎么撸代码吧关于 node 自定义生成图片，有一个很好的 npm 包，叫做 node-canvas，它可以让你在 node 中像在浏览器中一样绘制图像，诸如常见的 drawImage、fillText、fillRect 这些方法都支持。所以使用 node 绘制图像就不成大问题了，但关键是怎么绘制。</p>
<h4 id="安装-node-canvas"><a href="#安装-node-canvas" class="headerlink" title="安装 node-canvas"></a>安装 node-canvas</h4><figure class="highlight mipsasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 安装基础依赖</span></span><br><span class="line"><span class="comment"># ubuntu</span></span><br><span class="line">sudo apt-get <span class="keyword">install </span>libcairo2-dev libjpeg-dev libpango1.<span class="number">0</span>-dev libgif-dev <span class="keyword">build-essential </span>g++</span><br><span class="line"><span class="comment"># mac OS</span></span><br><span class="line"><span class="keyword">brew </span><span class="keyword">install </span>pkg-<span class="built_in">config</span> cairo libpng <span class="keyword">jpeg </span>giflib</span><br><span class="line"></span><br><span class="line"><span class="comment"># 安装canvas</span></span><br><span class="line">npm <span class="keyword">install </span>canvas</span><br></pre></td></tr></table></figure>
<p>安装出现了问题或者想要知道更多关于 node-canvas 的信息，可以看看它的<a href="https://github.com/Automattic/node-canvas" target="_blank" rel="noopener">github 首页</a></p>
<h4 id="基础应用"><a href="#基础应用" class="headerlink" title="基础应用"></a>基础应用</h4><p>比如用 node-canvas 绘制一段文字</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Canvas  <span class="keyword">from</span> <span class="string">'canvas'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> canvas = new Canvas(<span class="number">300</span>, <span class="number">120</span>) <span class="comment">// 按照微信官方要求，长宽比5:4</span></span><br><span class="line"><span class="keyword">const</span> context = canvas.getContext(<span class="string">'2d'</span>)</span><br><span class="line">ctx.font = <span class="string">'14px "Microsoft YaHei"'</span> <span class="comment">// 统一使用微软雅黑字体</span></span><br><span class="line">context.fillText(<span class="string">'Hellow'</span>, <span class="number">84</span>, <span class="number">24</span>, <span class="number">204</span>)</span><br></pre></td></tr></table></figure>
<p>fillText 接受四个参数，第一个是需要绘制的文本，第二个和第三个参数是定义绘制的起始位置的 x 和 y 坐标，第四个参数用来控制绘制文本的最大宽度 maxWidth。想要绘制好一张图片，这些位置信息都是要自己计算的哦！</p>
<h4 id="drawImage-的说明"><a href="#drawImage-的说明" class="headerlink" title="drawImage 的说明"></a>drawImage 的说明</h4><p>在绘制书籍封面图片的时候就会使用到 drawImage 方法，但是 node-canvas 的 drawImage 方法在传递图片参数的时候只接收 Buffer 类型，所以这里就涉及到如何将网络图片(从数据库中取出的封面图片地址，例如：)转换成 Buffer 类型。我们使用 https 的内置包(如果你请求的图片地址是 http 的请使用 http 的内置包)请求封面图片地址，在拼装请求数据之后使用 Buffer.concat 方法将其装换成 Buffer 类型。另外应为是在 koa 的 router 中写的代码，所以面对这种异步回调类型的操作，需要使用 Promise。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// 将封面图片转成buffer格式，用于canvas绘制图片</span></span><br><span class="line">  https.get(thisBook.img_url, imgRes =&gt; &#123;</span><br><span class="line">    <span class="keyword">let</span> chunks = []; <span class="comment">// 用于保存网络请求不断加载传输的缓冲数据</span></span><br><span class="line">    <span class="keyword">let</span> size = <span class="number">0</span>; <span class="comment">// 保存缓冲数据的总长度</span></span><br><span class="line">    imgRes.on(<span class="string">'data'</span>, chunk =&gt; &#123;</span><br><span class="line">      <span class="comment">/**</span></span><br><span class="line"><span class="comment">       * 在进行网络请求时，会不断接收到数据(数据不是一次性获取到的)</span></span><br><span class="line"><span class="comment">       * node会把接收到的数据片段逐段的保存在缓冲区（Buffer）</span></span><br><span class="line"><span class="comment">       * 这些数据片段会形成一个个缓冲对象（即Buffer对象）</span></span><br><span class="line"><span class="comment">       * 而Buffer数据的拼接并不能像字符串那样拼接（因为一个中文字符占三个字节），</span></span><br><span class="line"><span class="comment">       * 如果一个数据片段携带着一个中文的两个字节，下一个数据片段携带着最后一个字节，</span></span><br><span class="line"><span class="comment">       * 直接字符串拼接会导致乱码，为避免乱码，所以将得到缓冲数据推入到chunks数组中，</span></span><br><span class="line"><span class="comment">       * 利用下面的node.js内置的Buffer.concat()方法进行拼接</span></span><br><span class="line"><span class="comment">       */</span></span><br><span class="line">      chunks.push(chunk);</span><br><span class="line">      size += chunk.length;</span><br><span class="line">    &#125;);</span><br><span class="line">    imgRes.on(<span class="string">'end'</span>, err =&gt; &#123;</span><br><span class="line">      <span class="keyword">if</span> (err) &#123;</span><br><span class="line">        ctx.body = &#123; <span class="attr">ok</span>: <span class="literal">false</span>, <span class="attr">msg</span>: <span class="string">'下载书籍封面图片失败'</span> &#125;;</span><br><span class="line">        reject(<span class="string">'下载书籍封面图片失败'</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">const</span> buffer = Buffer.concat(chunks, size);</span><br><span class="line">      <span class="comment">// 判断是否是一个buffer对象</span></span><br><span class="line">      <span class="keyword">if</span> (Buffer.isBuffer(buffer)) &#123;</span><br><span class="line">        <span class="comment">// 继续你的canvas绘画....</span></span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        ctx.body = &#123; <span class="attr">ok</span>: <span class="literal">false</span>, <span class="attr">msg</span>: <span class="string">'下载书籍封面图片失败'</span> &#125;;</span><br><span class="line">        reject(<span class="string">'下载书籍封面图片失败'</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h4 id="fillText-的说明"><a href="#fillText-的说明" class="headerlink" title="fillText 的说明"></a>fillText 的说明</h4><p>之前提到过 fillText 方法可以接受一个名为 maxWidth 的参数，一旦绘制的文本超过这个宽度就会自动换行。本来这个设计是很好的，但是实际使用过程中就会发现，自动换行的行高很大(大到影响美观)。而且通过 context.font 也没办做到控制行高，因为 line-height 和 font-size 在 context.font 中是同一个参数。既然这样，又只能自己想办法了。行高没法控制，就只能每次绘制一行文本，然后使用绘制的时候传入的起始位置的 y 坐标来控制两行之间的间距。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 首先对从数据库中读取到的文本去掉换行符和制表符这些</span></span><br><span class="line"><span class="keyword">const</span> noSpaceContent = thisBook.chapters[<span class="number">0</span>].content.replace(<span class="regexp">/(\n|\t|\r)/g</span>, <span class="string">''</span>);</span><br><span class="line"><span class="comment">// 使用canvas的measureText方法得到一个中文的宽度，然后用最大宽度除以它得到一行最多可容纳的字符数</span></span><br><span class="line"><span class="keyword">const</span> oneTextWidth = context.measureText(<span class="string">'测'</span>).width;</span><br><span class="line"><span class="keyword">const</span> oneLineMaxTextNumber = <span class="built_in">Math</span>.ceil(<span class="number">204</span> / oneTextWidth);</span><br><span class="line"><span class="comment">// 小说描述最大行数</span></span><br><span class="line"><span class="keyword">let</span> maxLineNumber = <span class="number">4</span>;</span><br><span class="line"><span class="comment">// 当前行数</span></span><br><span class="line"><span class="keyword">let</span> current = <span class="number">4</span>;</span><br><span class="line"><span class="keyword">while</span> (current &gt; <span class="number">0</span>) &#123;</span><br><span class="line">  <span class="keyword">let</span> tmpText = noSpaceContent.substring(oneLineMaxTextNumber * (maxLineNumber - current), oneLineMaxTextNumber * (maxLineNumber + <span class="number">1</span> - current));</span><br><span class="line">  <span class="comment">// 最后一行文字显示省略号</span></span><br><span class="line">  <span class="keyword">if</span> (current === <span class="number">1</span>) &#123;</span><br><span class="line">    tmpText = tmpText.substring(<span class="number">0</span>, tmpText.length - <span class="number">2</span>) + <span class="string">'...'</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  context.fillText(tmpText, <span class="number">84</span>, <span class="number">62</span> + (maxLineNumber - current) * <span class="number">15</span>, <span class="number">204</span>);</span><br><span class="line">  current--;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="图片上传七牛云"><a href="#图片上传七牛云" class="headerlink" title="图片上传七牛云"></a>图片上传七牛云</h3><p>我这里使用的<a href="https://www.npmjs.com/package/qn" target="_blank" rel="noopener">qn</a>的包，大家去官网看看应该就知道怎么用。为了防止自己忘记，这里贴下代码。首先将配置写到 config.js 里</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> config = &#123;</span><br><span class="line">	accessKey: <span class="string">'xxx'</span>, <span class="comment">//七牛账号的key值，https://portal.qiniu.com/user/key</span></span><br><span class="line">	secretKey: <span class="string">'xxx'</span>,</span><br><span class="line">	bucket: <span class="string">'upload'</span>, <span class="comment">//空间名称</span></span><br><span class="line">	isUseHttps: <span class="keyword">true</span>, <span class="comment">//配置使用https，并且对应到正确的区域，详情请查考https://github.com/gpake/qiniu-wxapp-sdk/blob/master/README.md</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">module</span>.<span class="keyword">exports</span> = config;</span><br></pre></td></tr></table></figure>
<p>然后初始化七牛配置</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> config <span class="keyword">from</span> <span class="string">'../config'</span></span><br><span class="line"><span class="keyword">import</span> qn <span class="keyword">from</span> <span class="string">'qn'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// qiniu上传设置</span></span><br><span class="line"><span class="keyword">const</span> client = qn.create(&#123;</span><br><span class="line">  accessKey: config.accessKey,</span><br><span class="line">  secretKey: config.secretKey,</span><br><span class="line">  bucket: <span class="string">'upload'</span>,</span><br><span class="line">  origin: <span class="string">'https://file.lantingshucheng.com'</span>,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>七牛云允许直接上传本地图片，也可以直接是图片的 buffer 对象，我们使用 node-canvas 提供的 toBuffer 方法直接将我们绘制的 canvas 转成 buffer 对象然后上传</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 上传图片到七牛云</span></span><br><span class="line">client.upload(canvas.toBuffer(), &#123;<span class="string">key:</span> <span class="string">'mbook/share/'</span> + uuid.v1() + <span class="string">'.png'</span> &#125;, function (err, result) &#123;</span><br><span class="line">  <span class="keyword">if</span> (err) &#123;</span><br><span class="line">    ctx.body = &#123; <span class="string">ok:</span> <span class="literal">false</span>, <span class="string">msg:</span> <span class="string">'分享图片导出失败'</span> &#125;</span><br><span class="line">    reject(<span class="string">'分享图片导出失败'</span>)</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">  &#125;</span><br><span class="line">  ctx.body = &#123; <span class="string">ok:</span> <span class="literal">true</span>, <span class="string">msg:</span> <span class="string">'分享图片导出成功'</span>, <span class="string">url:</span> result.url &#125;</span><br><span class="line">  resolve(next())</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="效果图"><a href="#效果图" class="headerlink" title="效果图"></a>效果图</h3><p>是不是感觉还可以，哈哈~，完整代码请参考<a href="https://github.com/AndyliStudio/mbook-koa/blob/master/api/other.js" target="_blank" rel="noopener">这里</a><br><img src="https://file.lantingshucheng.com/mbook/share/fa4d3d10-463f-11e8-8a01-25d148dab515.png" alt="效果图"></p>

  </div>
  <div class="statement">
    <hr>  
    1. 如果本文帮到了您，不妨点一下右上角的”<i class="fas fa-share-alt"></i>“按钮。<br>
    2. 除非注明，本博文章均为原创，转载请以链接形式标明本文地址。<br>
    3. 如果你有任何疑问，欢迎发送邮件到我的邮箱<a href="mailto:andyliwr@outlook.com">andyliwr@outlook.com<br>
  </div>
</article>


    <div class="blog-post-comments">
        <div id="gitalk_thread">
            <noscript>加载评论需要在浏览器启用 JavaScript 脚本支持。</noscript>
        </div>
    </div>



        
          <div id="footer-post-container">
  <div id="footer-post">

    <div id="nav-footer" style="display: none">
      <ul>
         
          <li><a href="/">首页</a></li>
         
          <li><a href="/archives/">归档</a></li>
         
          <li><a href="/search/">搜索</a></li>
         
          <li><a href="/tags/">标签</a></li>
         
          <li><a href="/others/">其他文章</a></li>
        
      </ul>
    </div>

    <div id="toc-footer" style="display: none">
      <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#前言"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#阅读器页面分享"><span class="toc-number">1.1.</span> <span class="toc-text">阅读器页面分享</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#书籍详情页分享"><span class="toc-number">1.2.</span> <span class="toc-text">书籍详情页分享</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#小程序首页分享"><span class="toc-number">1.3.</span> <span class="toc-text">小程序首页分享</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#具体实现"><span class="toc-number">2.</span> <span class="toc-text">具体实现</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#安装-node-canvas"><span class="toc-number">2.1.</span> <span class="toc-text">安装 node-canvas</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#基础应用"><span class="toc-number">2.2.</span> <span class="toc-text">基础应用</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#drawImage-的说明"><span class="toc-number">2.3.</span> <span class="toc-text">drawImage 的说明</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#fillText-的说明"><span class="toc-number">2.4.</span> <span class="toc-text">fillText 的说明</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#图片上传七牛云"><span class="toc-number">3.</span> <span class="toc-text">图片上传七牛云</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#效果图"><span class="toc-number">4.</span> <span class="toc-text">效果图</span></a></li></ol>
    </div>

    <div id="share-footer" style="display: none">
      <ul>
  <li><a class="icon" href="http://www.facebook.com/sharer.php?u=https://andyliwr.github.io/2018/04/23/node_canvas_usage/"><i class="fab fa-facebook fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://twitter.com/share?url=https://andyliwr.github.io/2018/04/23/node_canvas_usage/&text=nodejs绘制生成图像"><i class="fab fa-twitter fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.linkedin.com/shareArticle?url=https://andyliwr.github.io/2018/04/23/node_canvas_usage/&title=nodejs绘制生成图像"><i class="fab fa-linkedin fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://pinterest.com/pin/create/bookmarklet/?url=https://andyliwr.github.io/2018/04/23/node_canvas_usage/&is_video=false&description=nodejs绘制生成图像"><i class="fab fa-pinterest fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=nodejs绘制生成图像&body=Check out this article: https://andyliwr.github.io/2018/04/23/node_canvas_usage/"><i class="fas fa-envelope fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://getpocket.com/save?url=https://andyliwr.github.io/2018/04/23/node_canvas_usage/&title=nodejs绘制生成图像"><i class="fab fa-get-pocket fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://reddit.com/submit?url=https://andyliwr.github.io/2018/04/23/node_canvas_usage/&title=nodejs绘制生成图像"><i class="fab fa-reddit fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.stumbleupon.com/submit?url=https://andyliwr.github.io/2018/04/23/node_canvas_usage/&title=nodejs绘制生成图像"><i class="fab fa-stumbleupon fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://digg.com/submit?url=https://andyliwr.github.io/2018/04/23/node_canvas_usage/&title=nodejs绘制生成图像"><i class="fab fa-digg fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.tumblr.com/share/link?url=https://andyliwr.github.io/2018/04/23/node_canvas_usage/&name=nodejs绘制生成图像&description="><i class="fab fa-tumblr fa-lg" aria-hidden="true"></i></a></li>
</ul>

    </div>

    <div id="actions-footer">
        <a id="menu" class="icon" href="#" onclick="$('#nav-footer').toggle();return false;"><i class="fas fa-bars fa-lg" aria-hidden="true"></i> 菜单</a>
        <a id="toc" class="icon" href="#" onclick="$('#toc-footer').toggle();return false;"><i class="fas fa-list fa-lg" aria-hidden="true"></i> 目录</a>
        <a id="share" class="icon" href="#" onclick="$('#share-footer').toggle();return false;"><i class="fas fa-share-alt fa-lg" aria-hidden="true"></i> 分享</a>
        <a id="top" style="display:none" class="icon" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up fa-lg" aria-hidden="true"></i> 返回顶部</a>
    </div>

  </div>
</div>

        
        <footer id="footer">
  <div class="footer-left">
    Copyright &copy; 2020 Dikang Li
  </div>
  <div class="footer-right">
    <nav>
      <ul>
         
          <li><a href="/">首页</a></li>
         
          <li><a href="/archives/">归档</a></li>
         
          <li><a href="/search/">搜索</a></li>
         
          <li><a href="/tags/">标签</a></li>
         
          <li><a href="/others/">其他文章</a></li>
        
      </ul>
    </nav>
  </div>
</footer>

    </div>
</body>
</html>
<!-- styles -->
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
<link rel="stylesheet" href="/lib/justified-gallery/css/justifiedGallery.min.css">
<link rel="stylesheet" href="/lib/fancybox/jquery.fancybox.css">

<link rel="stylesheet" href="https://file.lantingshucheng.com/blog/v3/static/styles/gitalk.css">


<!-- jquery -->
<script src="/lib/jquery/jquery.min.js"></script>
<script src="/lib/justified-gallery/js/jquery.justifiedGallery.min.js"></script>
<script src="/lib/fancybox/jquery.fancybox.pack.js"></script>

<script type="text/javascript" src="https://file.lantingshucheng.com/blog/v3/static/scripts/md5.js"></script>
<script type="text/javascript" src="https://file.lantingshucheng.com/blog/v3/static/scripts/gitalk.min.js"></script>

<script src="/js/main.js"></script>
<!-- search -->

<!-- Google Analytics -->

<!-- Baidu Analytics -->

    <script type="text/javascript">
        var _hmt = _hmt || [];
        (function() {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?7851ca7a86be957be994acb77639a5be";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        })();
    </script>

<!-- Disqus Comments -->


  <script type="text/javascript">
    window.onload = function(){
      if (window.location.href.indexOf('andyliwr.github.io') > -1) {
        var gitalk = new Gitalk({
          clientID: 'ad6f70df0c70d2b715f9',
          clientSecret: '40384bee244c1e17dd7c37733d21e9ef669e969c',
          repo: 'Andyliwr.github.io',
          owner: 'Andyliwr',
          admin: ['Andyliwr'],
          id: md5(location.pathname),
          distractionFreeMode: 'true'
        })
        gitalk.render('gitalk_thread')
      }
    }
  </script>


